package study.spring.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class JdbcServiceImpl implements JdbcService {

	private JdbcTemplate template;
	

	public void count() {
		String sql = "select count(*) from tbl_chouti_edit_link where name=?";
		int count = template.queryForInt(sql, new Object[] { "2" });
		System.out.println(count);
	}
	
	public void select(){
		String sql = "select id,name,img_url,url,clicks_count from tbl_chouti_edit_link where name='3'";
		Person t=template.queryForObject(sql, new RowMapper<Person>(){
			public Person mapRow(ResultSet rs, int rowNum)
					throws SQLException {
				Person t=new Person();
				t.setId(rs.getString(1));
				t.setName(rs.getString(2));
				t.setImg_url(rs.getString(3));
				t.setUrl(rs.getString(4));
				t.setClicks_count(rs.getString(5));
				return t;
			}
		});
		System.out.println(t);
	}
	
	public void update(){
		//该方法用于返回生成的主键
		final String sql="insert into tbl_chouti_edit_link(name) values (?)";
		final String name="4";
		KeyHolder keyHolder=new GeneratedKeyHolder();
		template.update(new PreparedStatementCreator() {
			
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				
				PreparedStatement ps=con.prepareStatement(sql,new String[]{"id"});
				ps.setString(1, name);
				
				return ps;
			}
		},  keyHolder);
		System.out.println(keyHolder.getKey());
	}
	

	// ============================
	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}


}
